Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [8]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [9]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[9]:
<matplotlib.image.AxesImage at 0x7fe57f9087f0>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [10]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[10]:
<matplotlib.image.AxesImage at 0x7fe57c034f60>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [11]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[11]:
<matplotlib.image.AxesImage at 0x7fe5747cccf8>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [12]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[12]:
<matplotlib.image.AxesImage at 0x7fe5747f6d68>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [13]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')
eyes = eye_cascade.detectMultiScale(image_with_detections)
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
print("Number of eyes: ", len(eyes))
for (x,y,w,h) in eyes:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (0,255,0), 1)


# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Number of eyes:  2
Out[13]:
<matplotlib.image.AxesImage at 0x7fe57479fa90>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [14]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)
    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    print("rval ",rval)
    
    # Keep the video stream open
    while rval:
        # Plot the image from camera with all the face and eye detections marked
        
        faces = face_cascade.detectMultiScale(frame)
        eyes = eye_cascade.detectMultiScale(frame)
        # draw faaces
        for (x,y,w,h) in faces:
            cv2.rectangle(frame, (x,y), (x+w,y+h),(255,0,0), 3)  
        
        # draw eyes
        for (x,y,w,h) in eyes:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 1)
    
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        #print("key ",key)
        if (key & 0xFF) == ord('q'): # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            vc.release()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
    
In [9]:
# Call the laptop camera face/eye detector function above
#laptop_camera_go()
In [10]:
#cv2.destroyAllWindows()

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [11]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[11]:
<matplotlib.image.AxesImage at 0x7f0ca49ddda0>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [18]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-efd93a2ebcb8> in <module>()
      1 # Convert the RGB  image to grayscale
----> 2 gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)
      3 
      4 # Extract the pre-trained face detector from an xml file
      5 face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

NameError: name 'image_with_noise' is not defined

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [13]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!
image_with_noise_copy = np.copy(image_with_noise)
In [14]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the resultfac
denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise_copy, None,15,10,7,21)
# Convert the RGB  image to grayscale
gray_denoised = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_denoised, 4, 6)

for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(denoised_image, (x,y), (x+w,y+h), (255,0,0), 3)

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(denoised_image)
    
Out[14]:
<matplotlib.image.AxesImage at 0x7f0ca4914160>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [15]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[15]:
<matplotlib.image.AxesImage at 0x7f0ca40482b0>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [16]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
kernel = np.ones((4,4,), np.float32) / 16
blur_image = cv2.filter2D(image, -1, kernel)
## TODO: Then perform Canny edge detection and display the output
blur_edges = cv2.Canny(blur_image, 100, 200)
dialate_blur = cv2.dilate(blur_edges, None)


# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(dialate_blur, cmap='gray')
Out[16]:
<matplotlib.image.AxesImage at 0x7f0c9c079cc0>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [17]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[17]:
<matplotlib.image.AxesImage at 0x7f0c7f7e43c8>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [18]:
## TODO: Implement face detection
image_copy = np.copy(image)
gray_img = cv2.cvtColor(image_copy, cv2.COLOR_RGB2GRAY)
kernel = np.ones((100,100), np.float32) / 10000
faces = face_cascade.detectMultiScale(gray_img, 1.2,5)
print(len(faces))
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
for (x,y,w,h) in faces:
    #blur_area = cv2.filter2D(image_copy,-1, kernel)
    print(x,y,w,h)
    blur_area = cv2.filter2D(image_copy[y:y+h, x:x+w],-1, kernel)
    image_copy[y:y+h, x:x+w] = blur_area
    #cv2.rectangle(image_copy, (x,y), (x+w,y+h), (255,0,0), 3)
    ax1.imshow(image_copy, cmap='gray')
1
775 105 384 384
In [19]:
test_arr = np.array([
    [1,2,3],
    [2,3,4],
    [4,5,6]
])

test_arr[0:2,1:2]
Out[19]:
array([[2],
       [3]])

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [20]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        gray_img = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        kernel = np.ones((100,100), np.float32) / 10000
        faces = face_cascade.detectMultiScale(gray_img, 1.2,7)
        for (x,y,w,h) in faces:
            blur_area = cv2.filter2D(frame[y:y+h, x:x+w],-1, kernel)
            frame[y:y+h, x:x+w] = blur_area
        # Exit functionality - press any key to exit laptop video
        cv2.imshow("face detection activated", frame)
        key = cv2.waitKey(20)
        if (key & 0xFF) == ord('q'):
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [21]:
# Run laptop identity hider
#laptop_camera_go()

Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [1]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
Using TensorFlow backend.
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [23]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [19]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout, BatchNormalization, Activation
from keras.layers import Flatten, Dense


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def createCNNModel():
    model = Sequential()
    # CONV1
    model.add(Convolution2D(filters=16, 
                                    input_shape=(96,96,1),
                                    kernel_size=(3,3),
                                    padding='same', 
                                    name="conv1"))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2,2), name="maxpool1"))
    model.add(Dropout(0.3))
    # CONV 2
    model.add(Convolution2D(filters=32, kernel_size=(3,3),padding='same', name="conv2"))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2,2), name="maxpool2"))
    model.add(Dropout(0.3))

    # CONV3 
    model.add(Convolution2D(filters=64, kernel_size=(3,3),padding='same', name="conv3"))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2,2), name="maxpool3"))
    model.add(Dropout(0.3))
    # CONV4
    model.add(Convolution2D(filters=128, kernel_size=(3,3),padding='same', name="conv4"))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2,2), name="maxpool4"))
    model.add(Dropout(0.3))

    # FLatten layer of 512 
    model.add(Flatten())
    model.add(Dense(512))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.3))
    model.add(Dense(30))
    model.summary()
    return model

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

ADAM OPTIMIZATION

In [26]:
adam_model = createCNNModel()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1 (Conv2D)               (None, 96, 96, 16)        160       
_________________________________________________________________
batch_normalization_11 (Batc (None, 96, 96, 16)        64        
_________________________________________________________________
activation_11 (Activation)   (None, 96, 96, 16)        0         
_________________________________________________________________
maxpool1 (MaxPooling2D)      (None, 48, 48, 16)        0         
_________________________________________________________________
dropout_11 (Dropout)         (None, 48, 48, 16)        0         
_________________________________________________________________
conv2 (Conv2D)               (None, 48, 48, 32)        4640      
_________________________________________________________________
batch_normalization_12 (Batc (None, 48, 48, 32)        128       
_________________________________________________________________
activation_12 (Activation)   (None, 48, 48, 32)        0         
_________________________________________________________________
maxpool2 (MaxPooling2D)      (None, 24, 24, 32)        0         
_________________________________________________________________
dropout_12 (Dropout)         (None, 24, 24, 32)        0         
_________________________________________________________________
conv3 (Conv2D)               (None, 24, 24, 64)        18496     
_________________________________________________________________
batch_normalization_13 (Batc (None, 24, 24, 64)        256       
_________________________________________________________________
activation_13 (Activation)   (None, 24, 24, 64)        0         
_________________________________________________________________
maxpool3 (MaxPooling2D)      (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_13 (Dropout)         (None, 12, 12, 64)        0         
_________________________________________________________________
conv4 (Conv2D)               (None, 12, 12, 128)       73856     
_________________________________________________________________
batch_normalization_14 (Batc (None, 12, 12, 128)       512       
_________________________________________________________________
activation_14 (Activation)   (None, 12, 12, 128)       0         
_________________________________________________________________
maxpool4 (MaxPooling2D)      (None, 6, 6, 128)         0         
_________________________________________________________________
dropout_14 (Dropout)         (None, 6, 6, 128)         0         
_________________________________________________________________
flatten_3 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 512)               2359808   
_________________________________________________________________
batch_normalization_15 (Batc (None, 512)               2048      
_________________________________________________________________
activation_15 (Activation)   (None, 512)               0         
_________________________________________________________________
dropout_15 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 30)                15390     
=================================================================
Total params: 2,475,358
Trainable params: 2,473,854
Non-trainable params: 1,504
_________________________________________________________________
In [27]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam

## TODO: Compile the model
adam_model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])

## TODO: Train the model
adam_hist = adam_model.fit(x=X_train, y=y_train, epochs=150, batch_size=32, validation_split=0.2)

## TODO: Save the model as model.h5
adam_model.save('adam_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/150
1712/1712 [==============================] - 2s - loss: 0.5364 - acc: 0.1343 - val_loss: 0.0398 - val_acc: 0.0444
Epoch 2/150
1712/1712 [==============================] - 2s - loss: 0.2723 - acc: 0.1922 - val_loss: 0.0487 - val_acc: 0.6893
Epoch 3/150
1712/1712 [==============================] - 2s - loss: 0.2017 - acc: 0.1968 - val_loss: 0.0249 - val_acc: 0.5935
Epoch 4/150
1712/1712 [==============================] - 2s - loss: 0.1599 - acc: 0.2436 - val_loss: 0.0143 - val_acc: 0.2523
Epoch 5/150
1712/1712 [==============================] - 2s - loss: 0.1302 - acc: 0.2617 - val_loss: 0.0091 - val_acc: 0.2523
Epoch 6/150
1712/1712 [==============================] - 2s - loss: 0.1005 - acc: 0.2710 - val_loss: 0.0076 - val_acc: 0.6963
Epoch 7/150
1712/1712 [==============================] - 2s - loss: 0.0838 - acc: 0.3049 - val_loss: 0.0070 - val_acc: 0.6963
Epoch 8/150
1712/1712 [==============================] - 2s - loss: 0.0707 - acc: 0.3002 - val_loss: 0.0057 - val_acc: 0.6893
Epoch 9/150
1712/1712 [==============================] - 2s - loss: 0.0569 - acc: 0.3458 - val_loss: 0.0070 - val_acc: 0.6612
Epoch 10/150
1712/1712 [==============================] - 2s - loss: 0.0476 - acc: 0.3481 - val_loss: 0.0071 - val_acc: 0.6893
Epoch 11/150
1712/1712 [==============================] - 2s - loss: 0.0402 - acc: 0.3738 - val_loss: 0.0065 - val_acc: 0.6682
Epoch 12/150
1712/1712 [==============================] - 2s - loss: 0.0347 - acc: 0.3651 - val_loss: 0.0065 - val_acc: 0.6565
Epoch 13/150
1712/1712 [==============================] - 2s - loss: 0.0298 - acc: 0.3820 - val_loss: 0.0082 - val_acc: 0.6822
Epoch 14/150
1712/1712 [==============================] - 2s - loss: 0.0252 - acc: 0.4019 - val_loss: 0.0064 - val_acc: 0.6916
Epoch 15/150
1712/1712 [==============================] - 2s - loss: 0.0218 - acc: 0.4428 - val_loss: 0.0056 - val_acc: 0.6893
Epoch 16/150
1712/1712 [==============================] - 2s - loss: 0.0192 - acc: 0.4498 - val_loss: 0.0062 - val_acc: 0.6893
Epoch 17/150
1712/1712 [==============================] - 2s - loss: 0.0169 - acc: 0.4650 - val_loss: 0.0062 - val_acc: 0.6939
Epoch 18/150
1712/1712 [==============================] - 2s - loss: 0.0146 - acc: 0.5018 - val_loss: 0.0054 - val_acc: 0.7009
Epoch 19/150
1712/1712 [==============================] - 2s - loss: 0.0133 - acc: 0.5105 - val_loss: 0.0053 - val_acc: 0.6986
Epoch 20/150
1712/1712 [==============================] - 2s - loss: 0.0123 - acc: 0.5088 - val_loss: 0.0056 - val_acc: 0.6963
Epoch 21/150
1712/1712 [==============================] - 2s - loss: 0.0110 - acc: 0.5374 - val_loss: 0.0047 - val_acc: 0.6963
Epoch 22/150
1712/1712 [==============================] - 2s - loss: 0.0100 - acc: 0.5584 - val_loss: 0.0046 - val_acc: 0.6939
Epoch 23/150
1712/1712 [==============================] - 2s - loss: 0.0090 - acc: 0.5905 - val_loss: 0.0045 - val_acc: 0.6939
Epoch 24/150
1712/1712 [==============================] - 2s - loss: 0.0084 - acc: 0.5987 - val_loss: 0.0044 - val_acc: 0.6939
Epoch 25/150
1712/1712 [==============================] - 2s - loss: 0.0078 - acc: 0.5964 - val_loss: 0.0048 - val_acc: 0.6963
Epoch 26/150
1712/1712 [==============================] - 2s - loss: 0.0074 - acc: 0.6139 - val_loss: 0.0046 - val_acc: 0.6939
Epoch 27/150
1712/1712 [==============================] - 2s - loss: 0.0068 - acc: 0.6157 - val_loss: 0.0044 - val_acc: 0.6729
Epoch 28/150
1712/1712 [==============================] - 2s - loss: 0.0065 - acc: 0.6215 - val_loss: 0.0043 - val_acc: 0.6916
Epoch 29/150
1712/1712 [==============================] - 2s - loss: 0.0064 - acc: 0.6478 - val_loss: 0.0042 - val_acc: 0.6916
Epoch 30/150
1712/1712 [==============================] - 2s - loss: 0.0060 - acc: 0.6489 - val_loss: 0.0046 - val_acc: 0.6963
Epoch 31/150
1712/1712 [==============================] - 2s - loss: 0.0057 - acc: 0.6478 - val_loss: 0.0042 - val_acc: 0.6916
Epoch 32/150
1712/1712 [==============================] - 2s - loss: 0.0055 - acc: 0.6711 - val_loss: 0.0042 - val_acc: 0.6916
Epoch 33/150
1712/1712 [==============================] - 2s - loss: 0.0053 - acc: 0.6741 - val_loss: 0.0042 - val_acc: 0.6963
Epoch 34/150
1712/1712 [==============================] - 2s - loss: 0.0051 - acc: 0.6717 - val_loss: 0.0042 - val_acc: 0.6869
Epoch 35/150
1712/1712 [==============================] - 2s - loss: 0.0051 - acc: 0.6787 - val_loss: 0.0042 - val_acc: 0.6916
Epoch 36/150
1712/1712 [==============================] - 2s - loss: 0.0049 - acc: 0.6799 - val_loss: 0.0041 - val_acc: 0.6822
Epoch 37/150
1712/1712 [==============================] - 2s - loss: 0.0047 - acc: 0.6863 - val_loss: 0.0040 - val_acc: 0.6963
Epoch 38/150
1712/1712 [==============================] - 2s - loss: 0.0047 - acc: 0.6799 - val_loss: 0.0040 - val_acc: 0.6916
Epoch 39/150
1712/1712 [==============================] - 2s - loss: 0.0047 - acc: 0.6840 - val_loss: 0.0041 - val_acc: 0.6963
Epoch 40/150
1712/1712 [==============================] - 2s - loss: 0.0045 - acc: 0.6840 - val_loss: 0.0041 - val_acc: 0.6939
Epoch 41/150
1712/1712 [==============================] - 2s - loss: 0.0045 - acc: 0.6729 - val_loss: 0.0040 - val_acc: 0.6939
Epoch 42/150
1712/1712 [==============================] - 2s - loss: 0.0043 - acc: 0.7009 - val_loss: 0.0039 - val_acc: 0.6939
Epoch 43/150
1712/1712 [==============================] - 2s - loss: 0.0042 - acc: 0.6875 - val_loss: 0.0038 - val_acc: 0.6963
Epoch 44/150
1712/1712 [==============================] - 2s - loss: 0.0043 - acc: 0.6992 - val_loss: 0.0038 - val_acc: 0.6963
Epoch 45/150
1712/1712 [==============================] - 2s - loss: 0.0043 - acc: 0.7044 - val_loss: 0.0037 - val_acc: 0.6822
Epoch 46/150
1712/1712 [==============================] - 2s - loss: 0.0040 - acc: 0.6945 - val_loss: 0.0039 - val_acc: 0.6939
Epoch 47/150
1712/1712 [==============================] - 2s - loss: 0.0040 - acc: 0.6893 - val_loss: 0.0038 - val_acc: 0.6963
Epoch 48/150
1712/1712 [==============================] - 2s - loss: 0.0039 - acc: 0.6992 - val_loss: 0.0037 - val_acc: 0.6939
Epoch 49/150
1712/1712 [==============================] - 2s - loss: 0.0039 - acc: 0.7091 - val_loss: 0.0036 - val_acc: 0.6963
Epoch 50/150
1712/1712 [==============================] - 2s - loss: 0.0038 - acc: 0.7009 - val_loss: 0.0034 - val_acc: 0.6939
Epoch 51/150
1712/1712 [==============================] - 2s - loss: 0.0038 - acc: 0.6957 - val_loss: 0.0035 - val_acc: 0.6939
Epoch 52/150
1712/1712 [==============================] - 2s - loss: 0.0037 - acc: 0.7074 - val_loss: 0.0034 - val_acc: 0.6963
Epoch 53/150
1712/1712 [==============================] - 2s - loss: 0.0038 - acc: 0.7126 - val_loss: 0.0034 - val_acc: 0.6963
Epoch 54/150
1712/1712 [==============================] - 2s - loss: 0.0036 - acc: 0.7027 - val_loss: 0.0033 - val_acc: 0.6963
Epoch 55/150
1712/1712 [==============================] - 2s - loss: 0.0035 - acc: 0.7167 - val_loss: 0.0033 - val_acc: 0.6986
Epoch 56/150
1712/1712 [==============================] - 2s - loss: 0.0035 - acc: 0.6998 - val_loss: 0.0031 - val_acc: 0.7009
Epoch 57/150
1712/1712 [==============================] - 2s - loss: 0.0034 - acc: 0.7039 - val_loss: 0.0031 - val_acc: 0.6939
Epoch 58/150
1712/1712 [==============================] - 2s - loss: 0.0034 - acc: 0.7109 - val_loss: 0.0029 - val_acc: 0.7009
Epoch 59/150
1712/1712 [==============================] - 2s - loss: 0.0032 - acc: 0.6951 - val_loss: 0.0029 - val_acc: 0.6986
Epoch 60/150
1712/1712 [==============================] - 2s - loss: 0.0033 - acc: 0.6916 - val_loss: 0.0030 - val_acc: 0.7079
Epoch 61/150
1712/1712 [==============================] - 2s - loss: 0.0032 - acc: 0.7015 - val_loss: 0.0029 - val_acc: 0.7009
Epoch 62/150
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7202 - val_loss: 0.0028 - val_acc: 0.7009
Epoch 63/150
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7202 - val_loss: 0.0029 - val_acc: 0.7056
Epoch 64/150
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7120 - val_loss: 0.0027 - val_acc: 0.7079
Epoch 65/150
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7144 - val_loss: 0.0027 - val_acc: 0.7056
Epoch 66/150
1712/1712 [==============================] - 2s - loss: 0.0030 - acc: 0.7079 - val_loss: 0.0027 - val_acc: 0.7407
Epoch 67/150
1712/1712 [==============================] - 2s - loss: 0.0029 - acc: 0.7085 - val_loss: 0.0026 - val_acc: 0.7009
Epoch 68/150
1712/1712 [==============================] - 2s - loss: 0.0028 - acc: 0.7114 - val_loss: 0.0027 - val_acc: 0.7360
Epoch 69/150
1712/1712 [==============================] - 2s - loss: 0.0028 - acc: 0.7301 - val_loss: 0.0025 - val_acc: 0.7126
Epoch 70/150
1712/1712 [==============================] - 2s - loss: 0.0027 - acc: 0.7255 - val_loss: 0.0025 - val_acc: 0.7033
Epoch 71/150
1712/1712 [==============================] - 2s - loss: 0.0028 - acc: 0.7150 - val_loss: 0.0026 - val_acc: 0.7523
Epoch 72/150
1712/1712 [==============================] - 2s - loss: 0.0028 - acc: 0.7331 - val_loss: 0.0024 - val_acc: 0.7500
Epoch 73/150
1712/1712 [==============================] - 2s - loss: 0.0027 - acc: 0.7220 - val_loss: 0.0024 - val_acc: 0.7009
Epoch 74/150
1712/1712 [==============================] - 2s - loss: 0.0026 - acc: 0.7220 - val_loss: 0.0023 - val_acc: 0.7336
Epoch 75/150
1712/1712 [==============================] - 2s - loss: 0.0026 - acc: 0.7331 - val_loss: 0.0024 - val_acc: 0.7407
Epoch 76/150
1712/1712 [==============================] - 2s - loss: 0.0026 - acc: 0.7272 - val_loss: 0.0025 - val_acc: 0.7220
Epoch 77/150
1712/1712 [==============================] - 2s - loss: 0.0026 - acc: 0.7290 - val_loss: 0.0025 - val_acc: 0.7453
Epoch 78/150
1712/1712 [==============================] - 2s - loss: 0.0024 - acc: 0.7237 - val_loss: 0.0022 - val_acc: 0.7103
Epoch 79/150
1712/1712 [==============================] - 2s - loss: 0.0025 - acc: 0.7336 - val_loss: 0.0021 - val_acc: 0.7313
Epoch 80/150
1712/1712 [==============================] - 2s - loss: 0.0024 - acc: 0.7331 - val_loss: 0.0022 - val_acc: 0.7360
Epoch 81/150
1712/1712 [==============================] - 2s - loss: 0.0024 - acc: 0.7266 - val_loss: 0.0022 - val_acc: 0.7079
Epoch 82/150
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7459 - val_loss: 0.0020 - val_acc: 0.7360
Epoch 83/150
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7418 - val_loss: 0.0021 - val_acc: 0.7710
Epoch 84/150
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7348 - val_loss: 0.0020 - val_acc: 0.7477
Epoch 85/150
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7296 - val_loss: 0.0020 - val_acc: 0.7336
Epoch 86/150
1712/1712 [==============================] - 2s - loss: 0.0022 - acc: 0.7430 - val_loss: 0.0021 - val_acc: 0.7266
Epoch 87/150
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7407 - val_loss: 0.0019 - val_acc: 0.7360
Epoch 88/150
1712/1712 [==============================] - 2s - loss: 0.0022 - acc: 0.7424 - val_loss: 0.0019 - val_acc: 0.7360
Epoch 89/150
1712/1712 [==============================] - 2s - loss: 0.0022 - acc: 0.7494 - val_loss: 0.0019 - val_acc: 0.7383
Epoch 90/150
1712/1712 [==============================] - 2s - loss: 0.0022 - acc: 0.7407 - val_loss: 0.0019 - val_acc: 0.7430
Epoch 91/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7377 - val_loss: 0.0022 - val_acc: 0.7313
Epoch 92/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7313 - val_loss: 0.0021 - val_acc: 0.7243
Epoch 93/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7360 - val_loss: 0.0019 - val_acc: 0.7313
Epoch 94/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7442 - val_loss: 0.0019 - val_acc: 0.7547
Epoch 95/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7506 - val_loss: 0.0019 - val_acc: 0.7453
Epoch 96/150
1712/1712 [==============================] - 2s - loss: 0.0020 - acc: 0.7547 - val_loss: 0.0019 - val_acc: 0.7477
Epoch 97/150
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7494 - val_loss: 0.0017 - val_acc: 0.7640
Epoch 98/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7477 - val_loss: 0.0017 - val_acc: 0.7150
Epoch 99/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7459 - val_loss: 0.0018 - val_acc: 0.7593
Epoch 100/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7611 - val_loss: 0.0017 - val_acc: 0.7477
Epoch 101/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7634 - val_loss: 0.0018 - val_acc: 0.7126
Epoch 102/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7541 - val_loss: 0.0017 - val_acc: 0.7617
Epoch 103/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7664 - val_loss: 0.0017 - val_acc: 0.7173
Epoch 104/150
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7447 - val_loss: 0.0017 - val_acc: 0.7453
Epoch 105/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7611 - val_loss: 0.0017 - val_acc: 0.7360
Epoch 106/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7512 - val_loss: 0.0016 - val_acc: 0.7570
Epoch 107/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7570 - val_loss: 0.0016 - val_acc: 0.7547
Epoch 108/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7634 - val_loss: 0.0018 - val_acc: 0.7407
Epoch 109/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7687 - val_loss: 0.0018 - val_acc: 0.7290
Epoch 110/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7529 - val_loss: 0.0017 - val_acc: 0.7640
Epoch 111/150
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7664 - val_loss: 0.0015 - val_acc: 0.7453
Epoch 112/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7605 - val_loss: 0.0017 - val_acc: 0.7360
Epoch 113/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7605 - val_loss: 0.0015 - val_acc: 0.7710
Epoch 114/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7605 - val_loss: 0.0015 - val_acc: 0.7336
Epoch 115/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7664 - val_loss: 0.0017 - val_acc: 0.7383
Epoch 116/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7710 - val_loss: 0.0017 - val_acc: 0.7430
Epoch 117/150
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7786 - val_loss: 0.0015 - val_acc: 0.7617
Epoch 118/150
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7634 - val_loss: 0.0015 - val_acc: 0.7780
Epoch 119/150
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7763 - val_loss: 0.0017 - val_acc: 0.7547
Epoch 120/150
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7710 - val_loss: 0.0016 - val_acc: 0.7313
Epoch 121/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7786 - val_loss: 0.0017 - val_acc: 0.7173
Epoch 122/150
1712/1712 [==============================] - 2s - loss: 0.0017 - acc: 0.7652 - val_loss: 0.0015 - val_acc: 0.7593
Epoch 123/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7687 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 124/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7757 - val_loss: 0.0015 - val_acc: 0.7664
Epoch 125/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7529 - val_loss: 0.0014 - val_acc: 0.7804
Epoch 126/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7687 - val_loss: 0.0015 - val_acc: 0.7897
Epoch 127/150
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7804 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 128/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7745 - val_loss: 0.0014 - val_acc: 0.7640
Epoch 129/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7798 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 130/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7599 - val_loss: 0.0013 - val_acc: 0.7617
Epoch 131/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7792 - val_loss: 0.0013 - val_acc: 0.7547
Epoch 132/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7769 - val_loss: 0.0012 - val_acc: 0.7593
Epoch 133/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7810 - val_loss: 0.0013 - val_acc: 0.7547
Epoch 134/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7763 - val_loss: 0.0016 - val_acc: 0.7477
Epoch 135/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7909 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 136/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7798 - val_loss: 0.0013 - val_acc: 0.7336
Epoch 137/150
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7856 - val_loss: 0.0013 - val_acc: 0.7523
Epoch 138/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7786 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 139/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7804 - val_loss: 0.0014 - val_acc: 0.7734
Epoch 140/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7704 - val_loss: 0.0013 - val_acc: 0.7593
Epoch 141/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7810 - val_loss: 0.0012 - val_acc: 0.7523
Epoch 142/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7786 - val_loss: 0.0014 - val_acc: 0.7570
Epoch 143/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7833 - val_loss: 0.0013 - val_acc: 0.7360
Epoch 144/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7926 - val_loss: 0.0014 - val_acc: 0.7664
Epoch 145/150
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7804 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 146/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.8002 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 147/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7967 - val_loss: 0.0014 - val_acc: 0.7477
Epoch 148/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7839 - val_loss: 0.0012 - val_acc: 0.7687
Epoch 149/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7938 - val_loss: 0.0012 - val_acc: 0.7617
Epoch 150/150
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7845 - val_loss: 0.0012 - val_acc: 0.7710

RMS Prop Optimization

In [25]:
rms_prop_model = createCNNModel()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1 (Conv2D)               (None, 96, 96, 16)        160       
_________________________________________________________________
batch_normalization_1 (Batch (None, 96, 96, 16)        64        
_________________________________________________________________
activation_1 (Activation)    (None, 96, 96, 16)        0         
_________________________________________________________________
maxpool1 (MaxPooling2D)      (None, 48, 48, 16)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 48, 48, 16)        0         
_________________________________________________________________
conv2 (Conv2D)               (None, 48, 48, 32)        4640      
_________________________________________________________________
batch_normalization_2 (Batch (None, 48, 48, 32)        128       
_________________________________________________________________
activation_2 (Activation)    (None, 48, 48, 32)        0         
_________________________________________________________________
maxpool2 (MaxPooling2D)      (None, 24, 24, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 24, 24, 32)        0         
_________________________________________________________________
conv3 (Conv2D)               (None, 24, 24, 64)        18496     
_________________________________________________________________
batch_normalization_3 (Batch (None, 24, 24, 64)        256       
_________________________________________________________________
activation_3 (Activation)    (None, 24, 24, 64)        0         
_________________________________________________________________
maxpool3 (MaxPooling2D)      (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
conv4 (Conv2D)               (None, 12, 12, 128)       73856     
_________________________________________________________________
batch_normalization_4 (Batch (None, 12, 12, 128)       512       
_________________________________________________________________
activation_4 (Activation)    (None, 12, 12, 128)       0         
_________________________________________________________________
maxpool4 (MaxPooling2D)      (None, 6, 6, 128)         0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 6, 6, 128)         0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               2359808   
_________________________________________________________________
batch_normalization_5 (Batch (None, 512)               2048      
_________________________________________________________________
activation_5 (Activation)    (None, 512)               0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 30)                15390     
=================================================================
Total params: 2,475,358
Trainable params: 2,473,854
Non-trainable params: 1,504
_________________________________________________________________
In [32]:
## TODO: Compile the model
rms_prop_model.compile(optimizer='rmsprop', loss='mean_squared_error', metrics=['accuracy'])

## TODO: Train the model
rms_prop_hist = rms_prop_model.fit(x=X_train, y=y_train, epochs=80, batch_size=32, validation_split=0.2)

## TODO: Save the model as model.h5
rms_prop_model.save('rms_prop_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/80
1712/1712 [==============================] - 2s - loss: 0.5633 - acc: 0.1355 - val_loss: 0.1917 - val_acc: 0.0000e+00
Epoch 2/80
1712/1712 [==============================] - 2s - loss: 0.2784 - acc: 0.1828 - val_loss: 0.0915 - val_acc: 0.0000e+00
Epoch 3/80
1712/1712 [==============================] - 2s - loss: 0.1721 - acc: 0.2097 - val_loss: 0.1012 - val_acc: 0.0000e+00
Epoch 4/80
1712/1712 [==============================] - 2s - loss: 0.0884 - acc: 0.2290 - val_loss: 0.0385 - val_acc: 0.3435
Epoch 5/80
1712/1712 [==============================] - 2s - loss: 0.0538 - acc: 0.3002 - val_loss: 0.0442 - val_acc: 0.6706
Epoch 6/80
1712/1712 [==============================] - 2s - loss: 0.0369 - acc: 0.3429 - val_loss: 0.0223 - val_acc: 0.0981
Epoch 7/80
1712/1712 [==============================] - 2s - loss: 0.0253 - acc: 0.4089 - val_loss: 0.0149 - val_acc: 0.4836
Epoch 8/80
1712/1712 [==============================] - 2s - loss: 0.0189 - acc: 0.4468 - val_loss: 0.0112 - val_acc: 0.3388
Epoch 9/80
1712/1712 [==============================] - 2s - loss: 0.0142 - acc: 0.5152 - val_loss: 0.0221 - val_acc: 0.4463
Epoch 10/80
1712/1712 [==============================] - 2s - loss: 0.0105 - acc: 0.5485 - val_loss: 0.0118 - val_acc: 0.6098
Epoch 11/80
1712/1712 [==============================] - 2s - loss: 0.0091 - acc: 0.6273 - val_loss: 0.0084 - val_acc: 0.6706
Epoch 12/80
1712/1712 [==============================] - 2s - loss: 0.0078 - acc: 0.6355 - val_loss: 0.0084 - val_acc: 0.6939
Epoch 13/80
1712/1712 [==============================] - 2s - loss: 0.0067 - acc: 0.6536 - val_loss: 0.0067 - val_acc: 0.6916
Epoch 14/80
1712/1712 [==============================] - 2s - loss: 0.0055 - acc: 0.6840 - val_loss: 0.0049 - val_acc: 0.7103
Epoch 15/80
1712/1712 [==============================] - 2s - loss: 0.0050 - acc: 0.7027 - val_loss: 0.0041 - val_acc: 0.6682
Epoch 16/80
1712/1712 [==============================] - 2s - loss: 0.0051 - acc: 0.6928 - val_loss: 0.0047 - val_acc: 0.7126
Epoch 17/80
1712/1712 [==============================] - 2s - loss: 0.0047 - acc: 0.7261 - val_loss: 0.0053 - val_acc: 0.6986
Epoch 18/80
1712/1712 [==============================] - 2s - loss: 0.0043 - acc: 0.7138 - val_loss: 0.0038 - val_acc: 0.6963
Epoch 19/80
1712/1712 [==============================] - 2s - loss: 0.0041 - acc: 0.7120 - val_loss: 0.0043 - val_acc: 0.7033
Epoch 20/80
1712/1712 [==============================] - 2s - loss: 0.0039 - acc: 0.7132 - val_loss: 0.0035 - val_acc: 0.7313
Epoch 21/80
1712/1712 [==============================] - 2s - loss: 0.0037 - acc: 0.7179 - val_loss: 0.0040 - val_acc: 0.7126
Epoch 22/80
1712/1712 [==============================] - 2s - loss: 0.0035 - acc: 0.7296 - val_loss: 0.0031 - val_acc: 0.7150
Epoch 23/80
1712/1712 [==============================] - 2s - loss: 0.0034 - acc: 0.7360 - val_loss: 0.0026 - val_acc: 0.7290
Epoch 24/80
1712/1712 [==============================] - 2s - loss: 0.0032 - acc: 0.7360 - val_loss: 0.0037 - val_acc: 0.7150
Epoch 25/80
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7389 - val_loss: 0.0026 - val_acc: 0.7360
Epoch 26/80
1712/1712 [==============================] - 2s - loss: 0.0031 - acc: 0.7348 - val_loss: 0.0025 - val_acc: 0.7196
Epoch 27/80
1712/1712 [==============================] - 2s - loss: 0.0030 - acc: 0.7377 - val_loss: 0.0028 - val_acc: 0.7383
Epoch 28/80
1712/1712 [==============================] - 2s - loss: 0.0028 - acc: 0.7465 - val_loss: 0.0025 - val_acc: 0.7290
Epoch 29/80
1712/1712 [==============================] - 2s - loss: 0.0027 - acc: 0.7459 - val_loss: 0.0024 - val_acc: 0.7640
Epoch 30/80
1712/1712 [==============================] - 2s - loss: 0.0027 - acc: 0.7547 - val_loss: 0.0024 - val_acc: 0.7196
Epoch 31/80
1712/1712 [==============================] - 2s - loss: 0.0025 - acc: 0.7553 - val_loss: 0.0025 - val_acc: 0.7290
Epoch 32/80
1712/1712 [==============================] - 2s - loss: 0.0025 - acc: 0.7471 - val_loss: 0.0024 - val_acc: 0.7523
Epoch 33/80
1712/1712 [==============================] - 2s - loss: 0.0024 - acc: 0.7658 - val_loss: 0.0029 - val_acc: 0.6192
Epoch 34/80
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7500 - val_loss: 0.0047 - val_acc: 0.7407
Epoch 35/80
1712/1712 [==============================] - 2s - loss: 0.0023 - acc: 0.7669 - val_loss: 0.0022 - val_acc: 0.7383
Epoch 36/80
1712/1712 [==============================] - 2s - loss: 0.0022 - acc: 0.7523 - val_loss: 0.0023 - val_acc: 0.7196
Epoch 37/80
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7529 - val_loss: 0.0026 - val_acc: 0.7290
Epoch 38/80
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7716 - val_loss: 0.0027 - val_acc: 0.7243
Epoch 39/80
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7658 - val_loss: 0.0021 - val_acc: 0.7383
Epoch 40/80
1712/1712 [==============================] - 2s - loss: 0.0021 - acc: 0.7623 - val_loss: 0.0023 - val_acc: 0.7056
Epoch 41/80
1712/1712 [==============================] - 2s - loss: 0.0020 - acc: 0.7693 - val_loss: 0.0018 - val_acc: 0.7313
Epoch 42/80
1712/1712 [==============================] - 2s - loss: 0.0020 - acc: 0.7553 - val_loss: 0.0019 - val_acc: 0.7033
Epoch 43/80
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7716 - val_loss: 0.0022 - val_acc: 0.7617
Epoch 44/80
1712/1712 [==============================] - 2s - loss: 0.0019 - acc: 0.7611 - val_loss: 0.0019 - val_acc: 0.7640
Epoch 45/80
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7646 - val_loss: 0.0021 - val_acc: 0.7570
Epoch 46/80
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7704 - val_loss: 0.0021 - val_acc: 0.7570
Epoch 47/80
1712/1712 [==============================] - 2s - loss: 0.0018 - acc: 0.7664 - val_loss: 0.0015 - val_acc: 0.7593
Epoch 48/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7699 - val_loss: 0.0015 - val_acc: 0.7827
Epoch 49/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7629 - val_loss: 0.0017 - val_acc: 0.7453
Epoch 50/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7804 - val_loss: 0.0016 - val_acc: 0.7617
Epoch 51/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7728 - val_loss: 0.0017 - val_acc: 0.7617
Epoch 52/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7716 - val_loss: 0.0017 - val_acc: 0.7664
Epoch 53/80
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7833 - val_loss: 0.0016 - val_acc: 0.7523
Epoch 54/80
1712/1712 [==============================] - 2s - loss: 0.0016 - acc: 0.7745 - val_loss: 0.0017 - val_acc: 0.7687
Epoch 55/80
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7932 - val_loss: 0.0016 - val_acc: 0.7804
Epoch 56/80
1712/1712 [==============================] - 2s - loss: 0.0015 - acc: 0.7710 - val_loss: 0.0017 - val_acc: 0.7547
Epoch 57/80
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.8026 - val_loss: 0.0016 - val_acc: 0.7664
Epoch 58/80
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7757 - val_loss: 0.0015 - val_acc: 0.7827
Epoch 59/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7769 - val_loss: 0.0013 - val_acc: 0.7687
Epoch 60/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7874 - val_loss: 0.0015 - val_acc: 0.7570
Epoch 61/80
1712/1712 [==============================] - 2s - loss: 0.0014 - acc: 0.7751 - val_loss: 0.0014 - val_acc: 0.7757
Epoch 62/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7961 - val_loss: 0.0018 - val_acc: 0.7383
Epoch 63/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7839 - val_loss: 0.0012 - val_acc: 0.7687
Epoch 64/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7973 - val_loss: 0.0013 - val_acc: 0.7664
Epoch 65/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.8014 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 66/80
1712/1712 [==============================] - 2s - loss: 0.0013 - acc: 0.7850 - val_loss: 0.0014 - val_acc: 0.7290
Epoch 67/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7862 - val_loss: 0.0013 - val_acc: 0.7617
Epoch 68/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7874 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 69/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.8002 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 70/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.8014 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 71/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7862 - val_loss: 0.0014 - val_acc: 0.7313
Epoch 72/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.8032 - val_loss: 0.0014 - val_acc: 0.7874
Epoch 73/80
1712/1712 [==============================] - 2s - loss: 0.0011 - acc: 0.8037 - val_loss: 0.0014 - val_acc: 0.7477
Epoch 74/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7821 - val_loss: 0.0012 - val_acc: 0.7664
Epoch 75/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.8032 - val_loss: 0.0011 - val_acc: 0.7734
Epoch 76/80
1712/1712 [==============================] - 2s - loss: 0.0011 - acc: 0.8061 - val_loss: 0.0012 - val_acc: 0.7734
Epoch 77/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7868 - val_loss: 0.0012 - val_acc: 0.7687
Epoch 78/80
1712/1712 [==============================] - 2s - loss: 0.0012 - acc: 0.7996 - val_loss: 0.0011 - val_acc: 0.7710
Epoch 79/80
1712/1712 [==============================] - 2s - loss: 0.0011 - acc: 0.8032 - val_loss: 0.0013 - val_acc: 0.7710
Epoch 80/80
1712/1712 [==============================] - 2s - loss: 0.0011 - acc: 0.7991 - val_loss: 0.0012 - val_acc: 0.7757

SGD Optimization

In [33]:
sgd_model = createCNNModel()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1 (Conv2D)               (None, 96, 96, 16)        160       
_________________________________________________________________
batch_normalization_26 (Batc (None, 96, 96, 16)        64        
_________________________________________________________________
activation_26 (Activation)   (None, 96, 96, 16)        0         
_________________________________________________________________
maxpool1 (MaxPooling2D)      (None, 48, 48, 16)        0         
_________________________________________________________________
dropout_26 (Dropout)         (None, 48, 48, 16)        0         
_________________________________________________________________
conv2 (Conv2D)               (None, 48, 48, 32)        4640      
_________________________________________________________________
batch_normalization_27 (Batc (None, 48, 48, 32)        128       
_________________________________________________________________
activation_27 (Activation)   (None, 48, 48, 32)        0         
_________________________________________________________________
maxpool2 (MaxPooling2D)      (None, 24, 24, 32)        0         
_________________________________________________________________
dropout_27 (Dropout)         (None, 24, 24, 32)        0         
_________________________________________________________________
conv3 (Conv2D)               (None, 24, 24, 64)        18496     
_________________________________________________________________
batch_normalization_28 (Batc (None, 24, 24, 64)        256       
_________________________________________________________________
activation_28 (Activation)   (None, 24, 24, 64)        0         
_________________________________________________________________
maxpool3 (MaxPooling2D)      (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_28 (Dropout)         (None, 12, 12, 64)        0         
_________________________________________________________________
conv4 (Conv2D)               (None, 12, 12, 128)       73856     
_________________________________________________________________
batch_normalization_29 (Batc (None, 12, 12, 128)       512       
_________________________________________________________________
activation_29 (Activation)   (None, 12, 12, 128)       0         
_________________________________________________________________
maxpool4 (MaxPooling2D)      (None, 6, 6, 128)         0         
_________________________________________________________________
dropout_29 (Dropout)         (None, 6, 6, 128)         0         
_________________________________________________________________
flatten_6 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_11 (Dense)             (None, 512)               2359808   
_________________________________________________________________
batch_normalization_30 (Batc (None, 512)               2048      
_________________________________________________________________
activation_30 (Activation)   (None, 512)               0         
_________________________________________________________________
dropout_30 (Dropout)         (None, 512)               0         
_________________________________________________________________
dense_12 (Dense)             (None, 30)                15390     
=================================================================
Total params: 2,475,358
Trainable params: 2,473,854
Non-trainable params: 1,504
_________________________________________________________________
In [34]:
## TODO: Compile the model
sgd_model.compile(optimizer='sgd', loss='mean_squared_error', metrics=['accuracy'])

## TODO: Train the model
sgd_hist = sgd_model.fit(x=X_train, y=y_train, epochs=150, batch_size=32, validation_split=0.2)

## TODO: Save the model as model.h5
sgd_model.save('sgd_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/150
1712/1712 [==============================] - 2s - loss: 1.0627 - acc: 0.0894 - val_loss: 0.1065 - val_acc: 0.1752
Epoch 2/150
1712/1712 [==============================] - 2s - loss: 0.7829 - acc: 0.1192 - val_loss: 0.0658 - val_acc: 0.1192
Epoch 3/150
1712/1712 [==============================] - 2s - loss: 0.6325 - acc: 0.1203 - val_loss: 0.0410 - val_acc: 0.0234
Epoch 4/150
1712/1712 [==============================] - 2s - loss: 0.5180 - acc: 0.1314 - val_loss: 0.0347 - val_acc: 0.0210
Epoch 5/150
1712/1712 [==============================] - 2s - loss: 0.4492 - acc: 0.1431 - val_loss: 0.0302 - val_acc: 0.0257
Epoch 6/150
1712/1712 [==============================] - 2s - loss: 0.4014 - acc: 0.1303 - val_loss: 0.0242 - val_acc: 0.0678
Epoch 7/150
1712/1712 [==============================] - 2s - loss: 0.3665 - acc: 0.1460 - val_loss: 0.0229 - val_acc: 0.0280
Epoch 8/150
1712/1712 [==============================] - 2s - loss: 0.3487 - acc: 0.1484 - val_loss: 0.0229 - val_acc: 0.0280
Epoch 9/150
1712/1712 [==============================] - 2s - loss: 0.3247 - acc: 0.1624 - val_loss: 0.0221 - val_acc: 0.0210
Epoch 10/150
1712/1712 [==============================] - 2s - loss: 0.3163 - acc: 0.1589 - val_loss: 0.0212 - val_acc: 0.0421
Epoch 11/150
1712/1712 [==============================] - 2s - loss: 0.2958 - acc: 0.1577 - val_loss: 0.0217 - val_acc: 0.0444
Epoch 12/150
1712/1712 [==============================] - 2s - loss: 0.2812 - acc: 0.1402 - val_loss: 0.0206 - val_acc: 0.0537
Epoch 13/150
1712/1712 [==============================] - 2s - loss: 0.2762 - acc: 0.1770 - val_loss: 0.0210 - val_acc: 0.0654
Epoch 14/150
1712/1712 [==============================] - 2s - loss: 0.2703 - acc: 0.1665 - val_loss: 0.0192 - val_acc: 0.1168
Epoch 15/150
1712/1712 [==============================] - 2s - loss: 0.2618 - acc: 0.1799 - val_loss: 0.0191 - val_acc: 0.4299
Epoch 16/150
1712/1712 [==============================] - 2s - loss: 0.2515 - acc: 0.1974 - val_loss: 0.0174 - val_acc: 0.3832
Epoch 17/150
1712/1712 [==============================] - 2s - loss: 0.2488 - acc: 0.1746 - val_loss: 0.0164 - val_acc: 0.3995
Epoch 18/150
1712/1712 [==============================] - 2s - loss: 0.2421 - acc: 0.1758 - val_loss: 0.0162 - val_acc: 0.2921
Epoch 19/150
1712/1712 [==============================] - 2s - loss: 0.2328 - acc: 0.1811 - val_loss: 0.0160 - val_acc: 0.3271
Epoch 20/150
1712/1712 [==============================] - 2s - loss: 0.2315 - acc: 0.1752 - val_loss: 0.0153 - val_acc: 0.4346
Epoch 21/150
1712/1712 [==============================] - 2s - loss: 0.2207 - acc: 0.1811 - val_loss: 0.0151 - val_acc: 0.4579
Epoch 22/150
1712/1712 [==============================] - 2s - loss: 0.2190 - acc: 0.1787 - val_loss: 0.0152 - val_acc: 0.4720
Epoch 23/150
1712/1712 [==============================] - 2s - loss: 0.2155 - acc: 0.1799 - val_loss: 0.0144 - val_acc: 0.3201
Epoch 24/150
1712/1712 [==============================] - 2s - loss: 0.2105 - acc: 0.1711 - val_loss: 0.0136 - val_acc: 0.4836
Epoch 25/150
1712/1712 [==============================] - 2s - loss: 0.2045 - acc: 0.1893 - val_loss: 0.0138 - val_acc: 0.4229
Epoch 26/150
1712/1712 [==============================] - 2s - loss: 0.1999 - acc: 0.1933 - val_loss: 0.0147 - val_acc: 0.2103
Epoch 27/150
1712/1712 [==============================] - 2s - loss: 0.1981 - acc: 0.1939 - val_loss: 0.0136 - val_acc: 0.2173
Epoch 28/150
1712/1712 [==============================] - 2s - loss: 0.1931 - acc: 0.1805 - val_loss: 0.0129 - val_acc: 0.5561
Epoch 29/150
1712/1712 [==============================] - 2s - loss: 0.1923 - acc: 0.1951 - val_loss: 0.0129 - val_acc: 0.5257
Epoch 30/150
1712/1712 [==============================] - 2s - loss: 0.1889 - acc: 0.1811 - val_loss: 0.0127 - val_acc: 0.5467
Epoch 31/150
1712/1712 [==============================] - 2s - loss: 0.1853 - acc: 0.2138 - val_loss: 0.0122 - val_acc: 0.5607
Epoch 32/150
1712/1712 [==============================] - 2s - loss: 0.1807 - acc: 0.2004 - val_loss: 0.0121 - val_acc: 0.5257
Epoch 33/150
1712/1712 [==============================] - 2s - loss: 0.1808 - acc: 0.1893 - val_loss: 0.0117 - val_acc: 0.5467
Epoch 34/150
1712/1712 [==============================] - 2s - loss: 0.1754 - acc: 0.1998 - val_loss: 0.0119 - val_acc: 0.3785
Epoch 35/150
1712/1712 [==============================] - 2s - loss: 0.1714 - acc: 0.1933 - val_loss: 0.0122 - val_acc: 0.5304
Epoch 36/150
1712/1712 [==============================] - 2s - loss: 0.1667 - acc: 0.1998 - val_loss: 0.0118 - val_acc: 0.5771
Epoch 37/150
1712/1712 [==============================] - 2s - loss: 0.1644 - acc: 0.2044 - val_loss: 0.0110 - val_acc: 0.5771
Epoch 38/150
1712/1712 [==============================] - 2s - loss: 0.1652 - acc: 0.2050 - val_loss: 0.0118 - val_acc: 0.5070
Epoch 39/150
1712/1712 [==============================] - 2s - loss: 0.1585 - acc: 0.2161 - val_loss: 0.0112 - val_acc: 0.5911
Epoch 40/150
1712/1712 [==============================] - 2s - loss: 0.1574 - acc: 0.2284 - val_loss: 0.0114 - val_acc: 0.5864
Epoch 41/150
1712/1712 [==============================] - 2s - loss: 0.1580 - acc: 0.2103 - val_loss: 0.0107 - val_acc: 0.5911
Epoch 42/150
1712/1712 [==============================] - 2s - loss: 0.1536 - acc: 0.2161 - val_loss: 0.0112 - val_acc: 0.5818
Epoch 43/150
1712/1712 [==============================] - 2s - loss: 0.1488 - acc: 0.2126 - val_loss: 0.0109 - val_acc: 0.5771
Epoch 44/150
1712/1712 [==============================] - 2s - loss: 0.1483 - acc: 0.2074 - val_loss: 0.0110 - val_acc: 0.6121
Epoch 45/150
1712/1712 [==============================] - 2s - loss: 0.1444 - acc: 0.1933 - val_loss: 0.0110 - val_acc: 0.6051
Epoch 46/150
1712/1712 [==============================] - 2s - loss: 0.1439 - acc: 0.2150 - val_loss: 0.0109 - val_acc: 0.5958
Epoch 47/150
1712/1712 [==============================] - 2s - loss: 0.1441 - acc: 0.2109 - val_loss: 0.0111 - val_acc: 0.5958
Epoch 48/150
1712/1712 [==============================] - 2s - loss: 0.1393 - acc: 0.2418 - val_loss: 0.0101 - val_acc: 0.6098
Epoch 49/150
1712/1712 [==============================] - 2s - loss: 0.1363 - acc: 0.2325 - val_loss: 0.0104 - val_acc: 0.5888
Epoch 50/150
1712/1712 [==============================] - 2s - loss: 0.1336 - acc: 0.2138 - val_loss: 0.0101 - val_acc: 0.6379
Epoch 51/150
1712/1712 [==============================] - 2s - loss: 0.1336 - acc: 0.2091 - val_loss: 0.0101 - val_acc: 0.6098
Epoch 52/150
1712/1712 [==============================] - 2s - loss: 0.1324 - acc: 0.2050 - val_loss: 0.0101 - val_acc: 0.6145
Epoch 53/150
1712/1712 [==============================] - 2s - loss: 0.1288 - acc: 0.2348 - val_loss: 0.0099 - val_acc: 0.6355
Epoch 54/150
1712/1712 [==============================] - 2s - loss: 0.1277 - acc: 0.2225 - val_loss: 0.0100 - val_acc: 0.6332
Epoch 55/150
1712/1712 [==============================] - 2s - loss: 0.1260 - acc: 0.2225 - val_loss: 0.0101 - val_acc: 0.5935
Epoch 56/150
1712/1712 [==============================] - 2s - loss: 0.1247 - acc: 0.2255 - val_loss: 0.0099 - val_acc: 0.6145
Epoch 57/150
1712/1712 [==============================] - 2s - loss: 0.1202 - acc: 0.2319 - val_loss: 0.0097 - val_acc: 0.6449
Epoch 58/150
1712/1712 [==============================] - 2s - loss: 0.1211 - acc: 0.2261 - val_loss: 0.0096 - val_acc: 0.6028
Epoch 59/150
1712/1712 [==============================] - 2s - loss: 0.1228 - acc: 0.2307 - val_loss: 0.0095 - val_acc: 0.6215
Epoch 60/150
1712/1712 [==============================] - 2s - loss: 0.1175 - acc: 0.2033 - val_loss: 0.0098 - val_acc: 0.6495
Epoch 61/150
1712/1712 [==============================] - 2s - loss: 0.1179 - acc: 0.2442 - val_loss: 0.0094 - val_acc: 0.6402
Epoch 62/150
1712/1712 [==============================] - 2s - loss: 0.1157 - acc: 0.2401 - val_loss: 0.0090 - val_acc: 0.6215
Epoch 63/150
1712/1712 [==============================] - 2s - loss: 0.1147 - acc: 0.2255 - val_loss: 0.0094 - val_acc: 0.6332
Epoch 64/150
1712/1712 [==============================] - 2s - loss: 0.1111 - acc: 0.2506 - val_loss: 0.0091 - val_acc: 0.6799
Epoch 65/150
1712/1712 [==============================] - 2s - loss: 0.1105 - acc: 0.2465 - val_loss: 0.0096 - val_acc: 0.6472
Epoch 66/150
1712/1712 [==============================] - 2s - loss: 0.1107 - acc: 0.2313 - val_loss: 0.0093 - val_acc: 0.6425
Epoch 67/150
1712/1712 [==============================] - 2s - loss: 0.1071 - acc: 0.2266 - val_loss: 0.0088 - val_acc: 0.6519
Epoch 68/150
1712/1712 [==============================] - 2s - loss: 0.1072 - acc: 0.2412 - val_loss: 0.0090 - val_acc: 0.6636
Epoch 69/150
1712/1712 [==============================] - 2s - loss: 0.1055 - acc: 0.2482 - val_loss: 0.0089 - val_acc: 0.6121
Epoch 70/150
1712/1712 [==============================] - 2s - loss: 0.1024 - acc: 0.2284 - val_loss: 0.0088 - val_acc: 0.6355
Epoch 71/150
1712/1712 [==============================] - 2s - loss: 0.1034 - acc: 0.2547 - val_loss: 0.0090 - val_acc: 0.6449
Epoch 72/150
1712/1712 [==============================] - 2s - loss: 0.1009 - acc: 0.2371 - val_loss: 0.0088 - val_acc: 0.6776
Epoch 73/150
1712/1712 [==============================] - 2s - loss: 0.1004 - acc: 0.2558 - val_loss: 0.0088 - val_acc: 0.6472
Epoch 74/150
1712/1712 [==============================] - 2s - loss: 0.1001 - acc: 0.2336 - val_loss: 0.0085 - val_acc: 0.6776
Epoch 75/150
1712/1712 [==============================] - 2s - loss: 0.0973 - acc: 0.2640 - val_loss: 0.0090 - val_acc: 0.6799
Epoch 76/150
1712/1712 [==============================] - 2s - loss: 0.0976 - acc: 0.2442 - val_loss: 0.0088 - val_acc: 0.6192
Epoch 77/150
1712/1712 [==============================] - 2s - loss: 0.0956 - acc: 0.2447 - val_loss: 0.0081 - val_acc: 0.6846
Epoch 78/150
1712/1712 [==============================] - 2s - loss: 0.0956 - acc: 0.2500 - val_loss: 0.0084 - val_acc: 0.6752
Epoch 79/150
1712/1712 [==============================] - 2s - loss: 0.0938 - acc: 0.2611 - val_loss: 0.0087 - val_acc: 0.6542
Epoch 80/150
1712/1712 [==============================] - 2s - loss: 0.0935 - acc: 0.2371 - val_loss: 0.0087 - val_acc: 0.6659
Epoch 81/150
1712/1712 [==============================] - 2s - loss: 0.0913 - acc: 0.2442 - val_loss: 0.0085 - val_acc: 0.6822
Epoch 82/150
1712/1712 [==============================] - 2s - loss: 0.0905 - acc: 0.2623 - val_loss: 0.0084 - val_acc: 0.6776
Epoch 83/150
1712/1712 [==============================] - 2s - loss: 0.0904 - acc: 0.2529 - val_loss: 0.0087 - val_acc: 0.6589
Epoch 84/150
1712/1712 [==============================] - 2s - loss: 0.0873 - acc: 0.2745 - val_loss: 0.0087 - val_acc: 0.6729
Epoch 85/150
1712/1712 [==============================] - 2s - loss: 0.0872 - acc: 0.2518 - val_loss: 0.0081 - val_acc: 0.6729
Epoch 86/150
1712/1712 [==============================] - 2s - loss: 0.0873 - acc: 0.2722 - val_loss: 0.0083 - val_acc: 0.6776
Epoch 87/150
1712/1712 [==============================] - 2s - loss: 0.0835 - acc: 0.2722 - val_loss: 0.0086 - val_acc: 0.6776
Epoch 88/150
1712/1712 [==============================] - 2s - loss: 0.0834 - acc: 0.2553 - val_loss: 0.0082 - val_acc: 0.6939
Epoch 89/150
1712/1712 [==============================] - 2s - loss: 0.0833 - acc: 0.2704 - val_loss: 0.0085 - val_acc: 0.6565
Epoch 90/150
1712/1712 [==============================] - 2s - loss: 0.0836 - acc: 0.2547 - val_loss: 0.0085 - val_acc: 0.6729
Epoch 91/150
1712/1712 [==============================] - 2s - loss: 0.0833 - acc: 0.2646 - val_loss: 0.0086 - val_acc: 0.6846
Epoch 92/150
1712/1712 [==============================] - 2s - loss: 0.0811 - acc: 0.2629 - val_loss: 0.0085 - val_acc: 0.6799
Epoch 93/150
1712/1712 [==============================] - 2s - loss: 0.0805 - acc: 0.2681 - val_loss: 0.0082 - val_acc: 0.6846
Epoch 94/150
1712/1712 [==============================] - 2s - loss: 0.0792 - acc: 0.2699 - val_loss: 0.0083 - val_acc: 0.6846
Epoch 95/150
1712/1712 [==============================] - 2s - loss: 0.0803 - acc: 0.2558 - val_loss: 0.0079 - val_acc: 0.6636
Epoch 96/150
1712/1712 [==============================] - 2s - loss: 0.0792 - acc: 0.2535 - val_loss: 0.0079 - val_acc: 0.6729
Epoch 97/150
1712/1712 [==============================] - 2s - loss: 0.0771 - acc: 0.2617 - val_loss: 0.0080 - val_acc: 0.6752
Epoch 98/150
1712/1712 [==============================] - 2s - loss: 0.0779 - acc: 0.2681 - val_loss: 0.0082 - val_acc: 0.6776
Epoch 99/150
1712/1712 [==============================] - 2s - loss: 0.0773 - acc: 0.2564 - val_loss: 0.0078 - val_acc: 0.6916
Epoch 100/150
1712/1712 [==============================] - 2s - loss: 0.0751 - acc: 0.2850 - val_loss: 0.0078 - val_acc: 0.6776
Epoch 101/150
1712/1712 [==============================] - 2s - loss: 0.0745 - acc: 0.2815 - val_loss: 0.0079 - val_acc: 0.6963
Epoch 102/150
1712/1712 [==============================] - 2s - loss: 0.0728 - acc: 0.2903 - val_loss: 0.0079 - val_acc: 0.6799
Epoch 103/150
1712/1712 [==============================] - 2s - loss: 0.0727 - acc: 0.2745 - val_loss: 0.0082 - val_acc: 0.6706
Epoch 104/150
1712/1712 [==============================] - 2s - loss: 0.0717 - acc: 0.2845 - val_loss: 0.0080 - val_acc: 0.6822
Epoch 105/150
1712/1712 [==============================] - 2s - loss: 0.0709 - acc: 0.2582 - val_loss: 0.0083 - val_acc: 0.6893
Epoch 106/150
1712/1712 [==============================] - 2s - loss: 0.0699 - acc: 0.2769 - val_loss: 0.0080 - val_acc: 0.6846
Epoch 107/150
1712/1712 [==============================] - 2s - loss: 0.0704 - acc: 0.2780 - val_loss: 0.0078 - val_acc: 0.6822
Epoch 108/150
1712/1712 [==============================] - 2s - loss: 0.0694 - acc: 0.2868 - val_loss: 0.0076 - val_acc: 0.6939
Epoch 109/150
1712/1712 [==============================] - 2s - loss: 0.0682 - acc: 0.2763 - val_loss: 0.0078 - val_acc: 0.6916
Epoch 110/150
1712/1712 [==============================] - 2s - loss: 0.0682 - acc: 0.2605 - val_loss: 0.0078 - val_acc: 0.6939
Epoch 111/150
1712/1712 [==============================] - 2s - loss: 0.0694 - acc: 0.2763 - val_loss: 0.0081 - val_acc: 0.6939
Epoch 112/150
1712/1712 [==============================] - 2s - loss: 0.0672 - acc: 0.2874 - val_loss: 0.0075 - val_acc: 0.6939
Epoch 113/150
1712/1712 [==============================] - 2s - loss: 0.0665 - acc: 0.3008 - val_loss: 0.0079 - val_acc: 0.6963
Epoch 114/150
1712/1712 [==============================] - 2s - loss: 0.0650 - acc: 0.3113 - val_loss: 0.0079 - val_acc: 0.6963
Epoch 115/150
1712/1712 [==============================] - 2s - loss: 0.0646 - acc: 0.2640 - val_loss: 0.0074 - val_acc: 0.6963
Epoch 116/150
1712/1712 [==============================] - 2s - loss: 0.0646 - acc: 0.3008 - val_loss: 0.0075 - val_acc: 0.6986
Epoch 117/150
1712/1712 [==============================] - 2s - loss: 0.0622 - acc: 0.2775 - val_loss: 0.0079 - val_acc: 0.6963
Epoch 118/150
1712/1712 [==============================] - 2s - loss: 0.0628 - acc: 0.2856 - val_loss: 0.0074 - val_acc: 0.6869
Epoch 119/150
1712/1712 [==============================] - 2s - loss: 0.0629 - acc: 0.2950 - val_loss: 0.0075 - val_acc: 0.6752
Epoch 120/150
1712/1712 [==============================] - 2s - loss: 0.0625 - acc: 0.2973 - val_loss: 0.0078 - val_acc: 0.6916
Epoch 121/150
1712/1712 [==============================] - 2s - loss: 0.0623 - acc: 0.3043 - val_loss: 0.0076 - val_acc: 0.6916
Epoch 122/150
1712/1712 [==============================] - 2s - loss: 0.0609 - acc: 0.2780 - val_loss: 0.0076 - val_acc: 0.7009
Epoch 123/150
1712/1712 [==============================] - 2s - loss: 0.0608 - acc: 0.2973 - val_loss: 0.0078 - val_acc: 0.6916
Epoch 124/150
1712/1712 [==============================] - 2s - loss: 0.0600 - acc: 0.3137 - val_loss: 0.0079 - val_acc: 0.6916
Epoch 125/150
1712/1712 [==============================] - 2s - loss: 0.0602 - acc: 0.2827 - val_loss: 0.0075 - val_acc: 0.6939
Epoch 126/150
1712/1712 [==============================] - 2s - loss: 0.0589 - acc: 0.3178 - val_loss: 0.0076 - val_acc: 0.6893
Epoch 127/150
1712/1712 [==============================] - 2s - loss: 0.0582 - acc: 0.2804 - val_loss: 0.0076 - val_acc: 0.7033
Epoch 128/150
1712/1712 [==============================] - 2s - loss: 0.0593 - acc: 0.2886 - val_loss: 0.0072 - val_acc: 0.6939
Epoch 129/150
1712/1712 [==============================] - 2s - loss: 0.0571 - acc: 0.2938 - val_loss: 0.0073 - val_acc: 0.6893
Epoch 130/150
1712/1712 [==============================] - 2s - loss: 0.0567 - acc: 0.3201 - val_loss: 0.0076 - val_acc: 0.6869
Epoch 131/150
1712/1712 [==============================] - 2s - loss: 0.0571 - acc: 0.3078 - val_loss: 0.0074 - val_acc: 0.6986
Epoch 132/150
1712/1712 [==============================] - 2s - loss: 0.0560 - acc: 0.3107 - val_loss: 0.0075 - val_acc: 0.6939
Epoch 133/150
1712/1712 [==============================] - 2s - loss: 0.0549 - acc: 0.3014 - val_loss: 0.0074 - val_acc: 0.6963
Epoch 134/150
1712/1712 [==============================] - 2s - loss: 0.0556 - acc: 0.3037 - val_loss: 0.0069 - val_acc: 0.6963
Epoch 135/150
1712/1712 [==============================] - 2s - loss: 0.0542 - acc: 0.2897 - val_loss: 0.0072 - val_acc: 0.7009
Epoch 136/150
1712/1712 [==============================] - 2s - loss: 0.0545 - acc: 0.3207 - val_loss: 0.0073 - val_acc: 0.6963
Epoch 137/150
1712/1712 [==============================] - 2s - loss: 0.0545 - acc: 0.3090 - val_loss: 0.0072 - val_acc: 0.6963
Epoch 138/150
1712/1712 [==============================] - 2s - loss: 0.0541 - acc: 0.3032 - val_loss: 0.0072 - val_acc: 0.7009
Epoch 139/150
1712/1712 [==============================] - 2s - loss: 0.0530 - acc: 0.3218 - val_loss: 0.0074 - val_acc: 0.6986
Epoch 140/150
1712/1712 [==============================] - 2s - loss: 0.0528 - acc: 0.2985 - val_loss: 0.0073 - val_acc: 0.6939
Epoch 141/150
1712/1712 [==============================] - 2s - loss: 0.0523 - acc: 0.3119 - val_loss: 0.0072 - val_acc: 0.6939
Epoch 142/150
1712/1712 [==============================] - 2s - loss: 0.0508 - acc: 0.3160 - val_loss: 0.0071 - val_acc: 0.6963
Epoch 143/150
1712/1712 [==============================] - 2s - loss: 0.0520 - acc: 0.3289 - val_loss: 0.0069 - val_acc: 0.6986
Epoch 144/150
1712/1712 [==============================] - 2s - loss: 0.0511 - acc: 0.3201 - val_loss: 0.0073 - val_acc: 0.6986
Epoch 145/150
1712/1712 [==============================] - 2s - loss: 0.0496 - acc: 0.3283 - val_loss: 0.0072 - val_acc: 0.6986
Epoch 146/150
1712/1712 [==============================] - 2s - loss: 0.0501 - acc: 0.3213 - val_loss: 0.0074 - val_acc: 0.6893
Epoch 147/150
1712/1712 [==============================] - 2s - loss: 0.0494 - acc: 0.3364 - val_loss: 0.0074 - val_acc: 0.7033
Epoch 148/150
1712/1712 [==============================] - 2s - loss: 0.0487 - acc: 0.3294 - val_loss: 0.0072 - val_acc: 0.7009
Epoch 149/150
1712/1712 [==============================] - 2s - loss: 0.0484 - acc: 0.3119 - val_loss: 0.0071 - val_acc: 0.7009
Epoch 150/150
1712/1712 [==============================] - 2s - loss: 0.0489 - acc: 0.3341 - val_loss: 0.0071 - val_acc: 0.6939

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer:

  • First, I decided the archiecture of the neural networks should be the multi-layer convolutional neural network with the last two layers are dense layers. And the last dense layer need to have output of size 30 to match with the number of facial keypoints.
  • Each CNN layer should use same padding in order to reserve spacial information during the convolute operation.
  • There is a trade off between the deep level of the network and training time. In other works, the more convolutional layers the more parameters to tune and training is going to be slow. However, the input size (96,96,1) is not too big and not too complex. Therefore, I dedcided to use only 4 convolution layers with number of filters started from 16 and double at each level.
  • Also, the second to last dense layer has output of 512 so the network can learn some more about feature relations.
  • Maxpool layers are also applied for outputs of all convolutional layers to reduce number of trained parameters as stated above the input is small so we do not need really complex network that might not perform too much better than a small network which can be trained really fast.
  • Apply other useful deep learning techniques to help the network learn better:
    • Apply Batch Normalization to help the network converge faster.
    • Apply Dropout to add even more non-linear relations in the network.
    • Apply Relu as it is a well-known activation function that has been proved working really well with CNN architecture.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer:

  • In order to evaluate performance of each optimizers, I decided to train the model witch each of the optimization methods: adam, rmsprop and sgd in order to have the correct evaluation. Each optimization is run with 100 epochs.
  • Adam and RMSProp have very comparable results however RMSProp requires less number of epoch (80 vs 150) to acheive the similar level of performance as Adam. On the other hand, SGD does not converge as fast as the other twos under the same number of epochs.
  • As a result, I pick RmsProp trained network to use for applications in the next part of the project

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [45]:
## TODO: Visualize the training and validation loss of your neural network 
# Pick rms_prop trained network as the model
model = rms_prop_model
history = rms_prop_hist

#plot accuracy history
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title("Model Accuracy")
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend(['train', 'val'],loc='lower right')
Out[45]:
<matplotlib.legend.Legend at 0x7f3ef3083128>
In [46]:
#plot Loss 
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title("Model Loss")
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(['train', 'val'],loc='lower right')
Out[46]:
<matplotlib.legend.Legend at 0x7f3ef304e390>

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: I did not notice any evidence of overfitting from the two plots above. Both validation loss and train loss decrease while validation accuracy and train accuracy increase.

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [20]:
model = createCNNModel()
model.load_weights('rms_prop_model.h5')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1 (Conv2D)               (None, 96, 96, 16)        160       
_________________________________________________________________
batch_normalization_1 (Batch (None, 96, 96, 16)        64        
_________________________________________________________________
activation_1 (Activation)    (None, 96, 96, 16)        0         
_________________________________________________________________
maxpool1 (MaxPooling2D)      (None, 48, 48, 16)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 48, 48, 16)        0         
_________________________________________________________________
conv2 (Conv2D)               (None, 48, 48, 32)        4640      
_________________________________________________________________
batch_normalization_2 (Batch (None, 48, 48, 32)        128       
_________________________________________________________________
activation_2 (Activation)    (None, 48, 48, 32)        0         
_________________________________________________________________
maxpool2 (MaxPooling2D)      (None, 24, 24, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 24, 24, 32)        0         
_________________________________________________________________
conv3 (Conv2D)               (None, 24, 24, 64)        18496     
_________________________________________________________________
batch_normalization_3 (Batch (None, 24, 24, 64)        256       
_________________________________________________________________
activation_3 (Activation)    (None, 24, 24, 64)        0         
_________________________________________________________________
maxpool3 (MaxPooling2D)      (None, 12, 12, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 12, 12, 64)        0         
_________________________________________________________________
conv4 (Conv2D)               (None, 12, 12, 128)       73856     
_________________________________________________________________
batch_normalization_4 (Batch (None, 12, 12, 128)       512       
_________________________________________________________________
activation_4 (Activation)    (None, 12, 12, 128)       0         
_________________________________________________________________
maxpool4 (MaxPooling2D)      (None, 6, 6, 128)         0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 6, 6, 128)         0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               2359808   
_________________________________________________________________
batch_normalization_5 (Batch (None, 512)               2048      
_________________________________________________________________
activation_5 (Activation)    (None, 512)               0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 30)                15390     
=================================================================
Total params: 2,475,358
Trainable params: 2,473,854
Non-trainable params: 1,504
_________________________________________________________________
In [21]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [22]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')


# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image)
Out[22]:
<matplotlib.image.AxesImage at 0x7fe56c1e29e8>
In [23]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
## TODO : Paint the predicted keypoints on the test image
image_copy = np.copy(image)
image_gray = cv2.cvtColor(image_copy, cv2.COLOR_RGB2GRAY)
faces = face_cascade.detectMultiScale(image_copy, 1.2,5)
print("Num faces: %d"%len(faces))
row = 1
col = 2
count = 1
fig=plt.figure(figsize=(8,8))
facial_key_point_list =[]
# get face and get result from model predict
for (x,y,w,h) in faces:
    #preprocessing face
    face = image_gray[y:y+h, x:x+w]
    face = cv2.resize(face, (96,96))
    fig.add_subplot(row, col,count)
    plt.imshow(face, cmap='gray')
    count += 1
    # normalize face
    face = face / 255
    facial_point = model.predict(face.reshape(-1,96,96,1))
    # recalculate facial point
    facial_point = facial_point.squeeze()
    facial_point = (facial_point * 48.0) + 48.0
    # scale facial keypoint back to ogirinal image
    facial_point[0::2] = facial_point[0::2] * w/96.0
    facial_point[0::2] += x
    facial_point[1::2] = facial_point[1::2] * h/96.0
    facial_point[1::2] += y
    facial_key_point_list.append(facial_point)
    #print(facial_point.shape)
Num faces: 2
In [24]:
# PLOT IMAGE WITH ORIGINAL 
fig = plt.figure(figsize = (11,11))
ax1 = fig.add_subplot(111)
ax1.set_title('Final Image Detection')
ax1.imshow(image)

for facial_key_point in facial_key_point_list:
    # scale the facial keypoint back to the correct position
    ax1.scatter(facial_key_point[0::2], 
         facial_key_point[1::2], 
         marker='o', 
         c='c',
         s=20)

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [64]:
import cv2
import time 
from keras.models import load_model
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        # plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [ ]:
# Run your keypoint face painter
#laptop_camera_go()

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [ ]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [ ]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [ ]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [ ]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
In [ ]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [ ]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [ ]:
# Load facial landmark detector model
model = load_model('my_model.h5')

# Run sunglasses painter
laptop_camera_go()